package net.adst.util;

import javax.swing.*;
import java.awt.*;
import java.util.Collection;

/**
 * Created with IntelliJ IDEA.
 * User: Администратор
 * Date: 02.03.13
 * Time: 20:25
 * To change this template use File | Settings | File Templates.
 */
public class WiderDropDownCombo extends JComboBox {

    private String type;
    private boolean layingOut = false;
    private int widestLengh = 0;
    private boolean wide = false;

    public WiderDropDownCombo(Object[] objs) {
        super(objs);
    }

    public WiderDropDownCombo() {
        super();
    }

    public boolean isWide() {
        return wide;
    }

    //Setting the JComboBox wide
    public void setWide(boolean wide) {
        this.wide = wide;
        widestLengh = getWidestItemWidth();
    }

    public Dimension getSize() {
        Dimension dim = super.getSize();
        if (!layingOut && isWide())
            dim.width = Math.max(widestLengh, dim.width);
        return dim;
    }

    public int getWidestItemWidth() {

//        int numOfItems = this.getItemCount();
//        Font font = this.getFont();
//        FontMetrics metrics = this.getFontMetrics(font);
//        int widest = 0;
//        for (int i = 0; i < numOfItems; i++) {
//            Object item = this.getItemAt(i);
//            int lineWidth = metrics.stringWidth(item.toString());
//            widest = Math.max(widest, lineWidth);
//        }

        return widestLengh;
    }

    public void setWidestLengh(int widestLengh) {
        this.widestLengh = widestLengh;
    }

    public void setWidestLengh(Collection<String> items) {
        Font font = this.getFont();
        FontMetrics metrics = this.getFontMetrics(font);
        int widest = 0;
        for (Object item : items) {
            int lineWidth = metrics.stringWidth(item.toString());
            widest = Math.max(widest, lineWidth);
        }
        this.widestLengh = widest + 5;
    }

    public void doLayout() {
        try {
            layingOut = true;
            super.doLayout();
        } finally {
            layingOut = false;
        }
    }

    public String getType() {
        return type;
    }

    public void setType(String t) {
        type = t;
    }

}
